<?php

namespace Modules\Chinadmin\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Modules\Chinadmin\Services\C;
use Modules\System\Services\Mds\MDSArray;

class Common extends Base
{

    public function __construct(){

    }

    /**
     * 万能更新值接口。
     * http://l.com/chinadmin/admin/common/update
     *
     * "model":"Modules\Chinadmin\Models\EmployeeModel",
     * "id_field":"employee_id",
     * "id_val":obj.data.employee_id,
     * "up_field":"status",
     * "up_val":2,
     *
     */
    public function update(Request $request){

        $i = $request->input();

        //这里要限制可修改的模型和数据，暂且不限制，后期添加限制。
        if(empty($i['model'])){
            mdsResponse(400,"必须传model");
        }

        //只执行允许的model
        $model = C::$m[$i['model']]??"";

        if(!empty($model)){
            $i['model'] = $model;
        }

        if(empty($i['id_field'])){
            mdsResponse(400,"必须传id_field");
        }
        if(empty($i['id_val'])){
            mdsResponse(400,"必须传id_val");
        }

        //修改单个数据
        if(isset($i['up_field'])){

            if(empty($i['up_field'])){
                mdsResponse(400,"必须传up_field");
            }
            if(empty($i['up_val'])){
                mdsResponse(400,"必须传up_val");
            }

            $i['up_arr'] = [
                $i['up_field'] => $i['up_val']
            ];

        }

        //修改多条数据
        if(empty($i['up_arr'])){
            mdsResponse(400,"必须传更新数据");
        }

        foreach($i['up_arr'] as $k => $v){
            if($v == 'ca_date'){  //如果是时间
                $i['up_arr'][$k] = date("Y-m-d H:i:s");
            }
        }

        $re = $i['model']::where(function($query) use ($i){
            if(gettype($i['id_val']) == "array"){
                $i['id_val'] = array_column($i['id_val'], $i['id_field']);
                $query->whereIn($i['id_field'],$i['id_val']);
            }else{
                $query->where($i['id_field'],$i['id_val']);
            }
        })->update($i['up_arr']);

        mds_if_response($re);

    }

}
